package com.vogue.supplymall.admin.business.domain.biz.impl;

import com.vogue.supplymall.account.domain.model.AdminUser;
import com.vogue.supplymall.admin.business.common.QRCodeUtils;
import com.vogue.supplymall.admin.business.common.UploadResourceUtils;
import com.vogue.supplymall.admin.business.domain.biz.AdminPrivatePlatformBiz;
import com.vogue.supplymall.admin.business.domain.model.AdminDict;
import com.vogue.supplymall.admin.business.domain.model.AdminPrivatePlatform;
import com.vogue.supplymall.admin.business.domain.model.AdminPrivatePlatformApp;
import com.vogue.supplymall.admin.business.domain.service.AdminDictService;
import com.vogue.supplymall.admin.business.domain.service.AdminPrivatePlatformAppService;
import com.vogue.supplymall.admin.business.domain.service.AdminPrivatePlatformService;
import com.vogue.supplymall.common.constant.ConstantBean;
import com.vogue.supplymall.common.domain.dto.admin.PrivatePlatformAppInfo;
import com.vogue.supplymall.common.domain.dto.admin.PrivatePlatformInfo;
import com.vogue.supplymall.common.exception.ParamErrorException;
import com.vogue.supplymall.common.exception.ParamIsExistException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * The type Admin private platform biz.
 *
 * @author zhangliang
 * @date Create in 2018-07-12
 */
@Service("adminPrivatePlatformBiz")
public class AdminPrivatePlatformBizImpl implements AdminPrivatePlatformBiz {
    public static final Logger LOGGER_ADMINPRIVATEPLATFORMBIZIMPL = LoggerFactory.getLogger(AdminPrivatePlatformBizImpl.class);

    @Resource
    private AdminPrivatePlatformService adminPrivatePlatformService;
    @Resource
    private AdminPrivatePlatformAppService adminPrivatePlatformAppService;
    @Resource
    private AdminDictService adminDictService;
    @Resource
    private UploadResourceUtils uploadResourceUtils;
    @Resource
    private QRCodeUtils qrCodeUtils;

    @Override
    public List<Map<String, Object>> findAllPrivatePlatform(PrivatePlatformInfo privatePlatformInfo) {
        List<Map<String, Object>> result = new ArrayList<>();
        String sql = " name like CONCAT('%',#{name},'%') ";
        Map<String, Object> para = new HashMap<>();
        para.put("name", privatePlatformInfo.getName());
        List<AdminPrivatePlatform> platforms = adminPrivatePlatformService.selectByWhr0(sql, para);
        for (AdminPrivatePlatform privatePlatform : platforms) {
            Map<String, Object> map = new HashMap<>();
            privatePlatform.setModifyDate(null);
            privatePlatform.setUpdateuser(null);
            privatePlatform.setUpdateuserid(null);
            map.put("privatePlatform", privatePlatform);
            List<AdminPrivatePlatformApp> apps = adminPrivatePlatformAppService.selectByWhr(" appid = " + privatePlatform.getId());
            if (apps.size() > 0) {
                for (AdminPrivatePlatformApp app : apps) {
                    app.setModifyDate(null);
                    app.setUpdateuser(null);
                    app.setUpdateuserid(null);
                    if (app.getType() == 1) {
                        map.put("ios", app);
                    }
                    if (app.getType() == 2) {
                        map.put("android", app);
                    }
                }
            }
            result.add(map);
        }
        LOGGER_ADMINPRIVATEPLATFORMBIZIMPL.info("查询私有化平台信息 size：" + result.size());
        return result;
    }

    @Override
    @Transactional
    public Long addPrivatePlatform(PrivatePlatformInfo privatePlatformInfo, AdminUser info) {
        Map<String, Object> para = new HashMap<>();
        para.put("code", privatePlatformInfo.getPlatform());
        para.put("name", privatePlatformInfo.getName());
        List<AdminDict> dicts = adminDictService.selectByWhr0("code = #{code} or name = #{name} and  type = 10", para);
        if (dicts.size() > 0) {
            for (AdminDict dict : dicts) {
                if (privatePlatformInfo.getName().equals(dict.getName())) {
                    throw new ParamIsExistException("平台名称");
                }
                if (privatePlatformInfo.getPlatform().equals(dict.getCode().toString())) {
                    throw new ParamIsExistException("内部码");
                }
            }

        }
        para.put("filename", privatePlatformInfo.getFilename());
        AdminPrivatePlatform adminPrivatePlatform = adminPrivatePlatformService.selectOneByWhr0("filename = #{filename}", para);
        if (null != adminPrivatePlatform) {
            throw new ParamIsExistException("文件名称");
        }
        String tName = "t" + privatePlatformInfo.getPlatform();
        tName = tName.substring(0, tName.length() - 1);
        String codeValue = privatePlatformInfo.getPlatform() + privatePlatformInfo.getFilename();
        // 保存私有平台信息
        AdminPrivatePlatform privatePlatform = new AdminPrivatePlatform();
        privatePlatform.setUpdateuserid(info.getId());
        privatePlatform.setUpdateuser(info.getLoginname());
        privatePlatform.setFilename(privatePlatformInfo.getFilename());
        privatePlatform.setName(privatePlatformInfo.getName());
        privatePlatform.setPlatform(Integer.valueOf(privatePlatformInfo.getPlatform()));
        privatePlatform.setUrl(privatePlatformInfo.getUrl());
        privatePlatform.setIsshow(privatePlatformInfo.getIsshow());
        privatePlatform.setTname(tName);
        privatePlatform.setCodevalue(DigestUtils.md5Hex(codeValue));
        // 2018/10/22 添加合并支付方式和延时入账方式
        privatePlatform.setPaytogether(privatePlatformInfo.getPaytogether());
        privatePlatform.setEntrymode(privatePlatformInfo.getEntrymode());
        privatePlatform = adminPrivatePlatformService.save(privatePlatform);
        LOGGER_ADMINPRIVATEPLATFORMBIZIMPL.info("添加私有化平台信息 name：" + privatePlatform.getName());
        // 保存字典信息
        AdminDict adminDict = new AdminDict();
        adminDict.setCode(Integer.valueOf(privatePlatformInfo.getPlatform()));
        adminDict.setName(privatePlatformInfo.getName());
        adminDict.setType(10);
        adminDictService.save(adminDict);
        LOGGER_ADMINPRIVATEPLATFORMBIZIMPL.info("添加字典信息 platform：" + adminDict.getName());
        return privatePlatform.getId();
    }

    @Override
    @Transactional
    public void updatePrivatePlatform(PrivatePlatformInfo privatePlatformInfo, AdminUser info) {
        List<PrivatePlatformAppInfo> appInfo = privatePlatformInfo.getAppInfo();
        for (PrivatePlatformAppInfo platformAppInfo : appInfo) {
            if (null == platformAppInfo.getId() ||
                    null == platformAppInfo.getVersion() ||
                    null == platformAppInfo.getType()) {
                throw new ParamErrorException("");
            }
            AdminPrivatePlatformApp platformApp = adminPrivatePlatformAppService.get(platformAppInfo.getId());
            if (!platformAppInfo.getVersion().equals(platformApp.getVersion())) {
                platformApp.setVersion(platformAppInfo.getVersion());
                platformApp.setModifyDate(new Date());
                adminPrivatePlatformAppService.update(platformApp);
                LOGGER_ADMINPRIVATEPLATFORMBIZIMPL.info("更新私有化平台app信息 typ：" + platformApp.getType());
            }
        }

        AdminPrivatePlatform privatePlatform = adminPrivatePlatformService.get(privatePlatformInfo.getId());
        privatePlatform.setName(privatePlatformInfo.getName());
        privatePlatform.setModifyDate(new Date());
        privatePlatform.setIsshow(privatePlatformInfo.getIsshow());
        if (StringUtils.isNotEmpty(privatePlatformInfo.getUrl())) {
            privatePlatform.setUrl(privatePlatformInfo.getUrl());
        }
        // 2018/10/22 添加合并支付方式和延时入账方式
        privatePlatform.setPaytogether(privatePlatformInfo.getPaytogether());
        privatePlatform.setEntrymode(privatePlatformInfo.getEntrymode());
        adminPrivatePlatformService.update(privatePlatform);
        LOGGER_ADMINPRIVATEPLATFORMBIZIMPL.info("更新私有化平台信息 name：" + privatePlatform.getName());
        if (!privatePlatform.getName().equals(privatePlatformInfo.getName())) {
            Map<String, Object> para = new HashMap<>();
            para.put("name", privatePlatform.getName());
            List<AdminDict> dicts = adminDictService.selectByWhr0(" name = #{name} and  type = 10", para);
            for (AdminDict dict : dicts) {
                dict.setModifyDate(new Date());
                dict.setName(privatePlatformInfo.getName());
                adminDictService.update(dict);
            }
        }
    }

    @Override
    public Map<String, String> uploadApp(PrivatePlatformAppInfo appInfo) {
        // app上传地址
        String downloadurl = uploadResourceUtils.uploadResource(appInfo);
        // 在线下载地址
        String onlineurl = "";
        // 二维码上传地址
        String qrcodeurl = "";
        // 上传ios包时不生成二维码
        if (appInfo.getType() != 1) {
            onlineurl = downloadurl;
            String qrUrl = downloadurl;
            if (appInfo.getType() == 3) {
                qrUrl = appInfo.getIosService() + onlineurl;
            }
            InputStream imgInputStream = qrCodeUtils.drawLogoQRCode(null, qrUrl);
            if (appInfo.getType() == 3) {
                onlineurl = ConstantBean.PLIST_PREFIX + onlineurl;
                downloadurl = "";
            }
            appInfo.setFileStream(imgInputStream);
            appInfo.setExtension("png");
            // 上传二维码图片
            qrcodeurl = uploadResourceUtils.uploadResourceWithInputstream(appInfo);
        }
        Map<String, String> data = new HashMap<>();
        data.put("downloadurl", downloadurl);
        data.put("onlineurl", onlineurl);
        data.put("qrcodeurl", qrcodeurl);
        return data;
    }

    @Override
    public void saveAppInfo(PrivatePlatformAppInfo appInfo, AdminUser info) {
        LOGGER_ADMINPRIVATEPLATFORMBIZIMPL.info(" 保存已上传的app start ");
        if (null == appInfo.getId()) {
            insertAppInfo(appInfo, info);
        } else {
            updateAppInfo(appInfo, info);
        }
        LOGGER_ADMINPRIVATEPLATFORMBIZIMPL.info(" 保存已上传的app end ");
    }

    private void updateAppInfo(PrivatePlatformAppInfo appInfo, AdminUser info) {
        AdminPrivatePlatformApp app = adminPrivatePlatformAppService.get(appInfo.getId());
        if (null != app) {
            app.setVersion(appInfo.getVersion());
            app.setAppid(appInfo.getAppid());
            if (StringUtils.isEmpty(appInfo.getDownloadurl())) {
                app.setDownloadurl("");
            } else {
                app.setDownloadurl(appInfo.getDownloadurl());
            }
            app.setOnlineurl(appInfo.getOnlineurl());
            app.setQrcodeurl(appInfo.getQrcodeurl());
            app.setType(appInfo.getType());
            if (StringUtils.isEmpty(appInfo.getMemo())) {
                app.setMemo("");
            } else {
                app.setMemo(appInfo.getMemo());
            }
            app.setUptime(new Date());
            app.setUpdateuserid(info.getId());
            app.setUpdateuser(info.getLoginname());
            app.setModifyDate(new Date());
            adminPrivatePlatformAppService.update(app);
            LOGGER_ADMINPRIVATEPLATFORMBIZIMPL.info(" app信息已存在，更新app信息 ");
        }
    }

    private void insertAppInfo(PrivatePlatformAppInfo appInfo, AdminUser info) {
        AdminPrivatePlatformApp app = new AdminPrivatePlatformApp();
        app.setVersion(appInfo.getVersion());
        app.setAppid(appInfo.getAppid());
        if (StringUtils.isEmpty(appInfo.getDownloadurl())) {
            app.setDownloadurl("");
        } else {
            app.setDownloadurl(appInfo.getDownloadurl());
        }
        app.setOnlineurl(appInfo.getOnlineurl());
        app.setQrcodeurl(appInfo.getQrcodeurl());
        app.setType(appInfo.getType());
        if (StringUtils.isEmpty(appInfo.getMemo())) {
            app.setMemo("");
        } else {
            app.setMemo(appInfo.getMemo());
        }
        app.setUptime(new Date());
        app.setUpdateuserid(info.getId());
        app.setUpdateuser(info.getLoginname());
        adminPrivatePlatformAppService.save(app);
        LOGGER_ADMINPRIVATEPLATFORMBIZIMPL.info(" app信息不存在，创建app信息 ");
    }

    @Override
    public List<Map<String, Object>> getDownloadPage(String name) {
        String sql = "SELECT ad.`name`,appa.type,appa.downloadurl,appa.onlineurl,appa.qrcodeurl,appa.version, " +
                " appa.memo,appa.uptime,app.filename,app.`name`,app.platform,app.url " +
                " FROM admin_private_platform app INNER JOIN admin_private_platform_app appa ON (app.id = appa.appid) " +
                " INNER JOIN admin_dict ad on(app.platform = ad.`code`) where app.filename = #{name} ";
        Map<String, String> para = new HashMap<>();
        para.put("name", name);
        List<Map<String, Object>> data = adminPrivatePlatformService.query0(sql, para);
        return data;
    }
}
